import React from 'react';
import ReactDOM from 'react-dom';
import element from './element';
let container = document.getElementById('root');
const PLACEMENT = 'PLACEMENT'

// fiber对象
let nextUnitOfWork = {
  stateNode: container,
  props: { children: [element] }
}

function workLoop(deadLine) {
  while (nextUnitOfWork) {
    nextUnitOfWork = performUnitOfWork(nextUnitOfWork)
  }
}

function performUnitOfWork(workingInProgressFiber) {
  beginWork(workingInProgressFiber);
  if (workingInProgressFiber.child) {
    return workingInProgressFiber.child // 有儿子返回儿子
  }
  while (workingInProgressFiber) {
    completeUnitOfWork(workingInProgressFiber);
    if (workingInProgressFiber.sibling) {
      return workingInProgressFiber.sibling // 有弟弟返回弟弟
    }
    workingInProgressFiber = workingInProgressFiber.return // 没有弟弟了指向父亲，找父亲的弟弟
  }
}

/**
 * 创建此fiber的真实dom，通过虚拟dom创建fiber树
 */
function beginWork(workingInProgressFiber) {
  console.log('beginWork', workingInProgressFiber.props.id)
  if (!workingInProgressFiber.stateNode) {
    workingInProgressFiber.stateNode = document.createElement(workingInProgressFiber.type)
    for (let key in workingInProgressFiber.props) {
      if (key !== 'children') {
        workingInProgressFiber.stateNode[key] = workingInProgressFiber.props[key]
      }
    }
  }
  // 创建子fiber
  let previousFiber
  workingInProgressFiber.props.children.forEach((child, index) => {
    let childFiber = {
      type: child.type,
      props: child.props,
      return: workingInProgressFiber,
      effectTag: 'PLACEMENT', // 副作用标记
      nextEffect: null // 下一个有副作用的节点
    }
    if (index === 0) {
      workingInProgressFiber.child = childFiber
    } else {
      previousFiber.sibling = childFiber
    }
    previousFiber = childFiber
  })
}

function completeUnitOfWork() {
  console.log('completeUnitOfWork')
}

// 虚拟dom
// let element = (
//   <div id="A1">
//     <div id="B1">
//       <div id="C1"></div>
//       <div id="C2"></div>
//     </div>
//     <div id="B2"></div>
//   </div>
// )

// console.log(JSON.stringify(element))

/**
 * 
 * @param {*} element  虚拟dom
 * @param {*} parentDom  真实父dom
 * 如果节点多，层级特别深，因为js是单线程，而且ui渲染和js是互斥的
 */
function render(element, parentDom) {
  // 创建真实dom元素
  let dom = document.createElement(element.type); //div

  // 处理属性
  Object.keys(element.props)
    .filter(key => key !== "children")
    .forEach(key => {
      dom[key] = element.props[key]
    })

  if (Array.isArray(element.props.children)) {
    // 递归将每个子虚拟 dom 变成真实 dom 插入到父 dom 节点里
    element.props.children.forEach(child => render(child, dom))
  }
  parentDom.appendChild(dom);
}

// render(element, document.getElementById('root'))